package com.itheima.consumer.controller;


import com.itheima.consumer.domain.Goods;

import com.itheima.consumer.feign.GoodsFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("order")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private GoodsFeignClient goodsFeignClient;

/*    @GetMapping("findId/{id}")
    public Goods findId(@PathVariable("id") int id){

        System.out.println("查询的id"+id);
        //远程调用Goods服务中的findOne接口
//        使用RestTemplate
//        1. 定义Bean  restTemplate
//        2. 注入Bean
//        3. 调用方法
        //相当于远程得到一个json数据,然后解析成一个对象
//        String url="http://localhost:8000/goods/findId/"+id;
//       Goods goods = restTemplate.getForObject(url, Goods.class);
//       return goods;

      *//*      动态从Eureka Server 中获取 provider 的 ip 和端口
             1. 注入 DiscoveryClient 对象.激活
             2. 调用方法
         *//*
        //获得provider 的 ip 和端口 当前Eureka  Instance实例信息配置
        List<ServiceInstance> instances = discoveryClient.getInstances("eureka-provider");
        if (instances==null||instances.size()==0){
            return null;

        }

        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url="http://"+host+":"+port+"/goods/findId/"+id;
        System.out.println(url);
        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;

    }*/


    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){

        /*
        String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
        // 3. 调用方法
        Goods goods = restTemplate.getForObject(url, Goods.class);

        return goods;*/

        Goods goods = goodsFeignClient.findGoodsById(id);

        return goods;
    }

    @GetMapping("/goods2/{id}")
    public Goods findGoodsById2(@PathVariable("id") int id){
        System.out.println("findGoodsById..."+id);
        String url = "http://EUREKA-PROVIDER/goods/findId/"+id;
        // 3. 调用方法
        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;
    }

}
